﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using DTcms.Core.API.Filters;
using DTcms.Core.Common.Emum;
using DTcms.Core.Common.Extensions;
using DTcms.Core.Common.Helper;
using DTcms.Core.IServices;
using DTcms.Core.Model.Models;
using DTcms.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;

namespace DTcms.Core.API.Controllers
{
    /// <summary>
    /// 会员附件下载记录
    /// </summary>
    [Area("api")]
    [Route("api/member/attach")]
    [ApiController]
    public class MemberAttachController : ControllerBase
    {
        private readonly IMemberAttachLogService _memberAttachLogService;
        private readonly IMapper _mapper;

        public MemberAttachController(IMemberAttachLogService memberAttachLogService, IMapper mapper)
        {
            _memberAttachLogService = memberAttachLogService;
            _mapper = mapper;
        }

        /// <summary>
        /// 根据ID获取数据
        /// 示例：/api/member/attach/1
        /// </summary>
        [HttpGet("{id}")]
        [Authorize]
        [AuthorizeFilter("MemberAttach", ActionType.View)]
        public async Task<IActionResult> GetById([FromRoute] long id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<MemberAttachLogDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //查询数据库获取实体
            var resultFrom = await _memberAttachLogService.QueryAsync(x => x.Id == id);
            if (resultFrom == null)
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            //根据字段进行塑形
            var result = resultFrom.ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取分页列表
        /// 示例：/api/member/attach?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet]
        [Authorize]
        [AuthorizeFilter("MemberAttach", ActionType.View)]
        public async Task<IActionResult> GetList([FromQuery] BaseParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy.IsNotNullOrEmpty()
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<MemberAttachLogDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<MemberAttachLogDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }

            //获取数据列表，如果ID大于0则查询该用户下所有的列表
            var list = await _memberAttachLogService.QueryPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => (searchParam.Keyword.IsNotNullOrEmpty() ? x.UserName.Contains(searchParam.Keyword) : true),
                searchParam.OrderBy.IsNotNullOrWhiteSpace() ? searchParam.OrderBy : "-AddTime,-Id"
                );
            if (list == null || list.Count() <= 0)
            {
                return NotFound(ResponseMessage.Error("暂无查询到记录"));
            }

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //根据字段进行塑形，注意因为没有使用AotoMapper，所以要转换成Enumerable
            var resultDto = list.AsEnumerable().ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }


        /// <summary>
        /// 添加一条记录
        /// 示例：/api/member/attach
        /// </summary>
        [HttpPost]
        [Authorize]
        [AuthorizeFilter("MemberAttach", ActionType.Add)]
        public async Task<IActionResult> Add([FromBody] MemberAttachLogEditDto modelDto)
        {
            //检查会员是否存在
            if (!await _memberAttachLogService.ExistsAsync<Members>(x => x.UserId == modelDto.UserId))
            {
                return NotFound(ResponseMessage.Error($"会员ID{modelDto.UserId}不存在"));
            }
            //获取文章附件信息
            var attachModel = await _memberAttachLogService.QueryAsync<ArticleAttach>(x => x.Id == modelDto.AttachId);
            if (attachModel == null)
            {
                return NotFound(ResponseMessage.Error($"附件{modelDto.AttachId}不存在或已删除"));
            }
            modelDto.FileName = attachModel.FileName;

            //映射成实体
            var model = _mapper.Map<MemberAttachLog>(modelDto);
            //写入数据库
            await _memberAttachLogService.AddAsync(model);
            //重新联合查询
            var result = await _memberAttachLogService.QueryAsync(x => x.Id == model.Id);
            return Ok(result);
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/api/member/attach/1
        /// </summary>
        [HttpDelete("{id}")]
        [Authorize]
        [AuthorizeFilter("MemberAttach", ActionType.Delete)]
        public async Task<IActionResult> Delete([FromRoute] long id)
        {
            //检查记录是否存在
            if (!await _memberAttachLogService.ExistsAsync<MemberAttachLog>(x => x.Id == id))
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            var result = await _memberAttachLogService.DeleteAsync<MemberAttachLog>(x => x.Id == id);

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录
        /// 示例：/api/member/attach?ids=1,2,3
        /// </summary>
        [HttpDelete]
        [Authorize]
        [AuthorizeFilter("MemberAttach", ActionType.Delete)]
        public async Task<IActionResult> DeleteByIds([FromQuery] string Ids)
        {
            //检查参数是否为空
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //将ID列表转换成IEnumerable
            var listIds = Ids.ToIEnumerable<long>();
            if (listIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行批量删除操作
            await _memberAttachLogService.DeleteAsync<MemberAttachLog>(x => listIds.Contains(x.Id));

            return NoContent();
        }
    }
}
